import React, { forwardRef, useImperativeHandle, useMemo, useContext } from 'react';
import { Form, Input, Button } from 'antd';
import { FormProps } from 'antd/lib/form/Form';
import { ProColumnsType, SearchConfig, SearchRef, formRef } from './type';
import commonFun from '/@/uilts/commonFunction';
import GlobalContext from './GlobalContext';

interface SearchBarProps<T> extends FormProps {
  formItems: ProColumnsType<T>;
  search?: SearchConfig | false;
  // eslint-disable-next-line no-unused-vars
  onSearch?: (values: Partial<T>, isReset: boolean) => void;
  // eslint-disable-next-line no-unused-vars
  onChangeSearch?: (changedValues: any, allValues: any) => void;
}

type TransformResult = {
  transformData: any;
  transformKey: string | null;
};
const SearchBar = forwardRef<SearchRef, SearchBarProps<any>>(
  ({ formItems, onSearch, search, onChangeSearch, ...formProps }: SearchBarProps<any>, ref) => {
    const { loading } = useContext(GlobalContext);
    const [form] = Form.useForm();
    //导入清楚对象为空的属性
    const { removeEmptyOrNull } = commonFun();
    //处理transform对values进行转换
    const transformVal = (keys: Record<string, any>): TransformResult => {
      let transformData: any = null;
      let transformKey: string | null = null;
      formItems.forEach(({ dataIndex, search }) => {
        // eslint-disable-next-line no-prototype-builtins
        if (keys.hasOwnProperty(dataIndex as any)) {
          const transformedValue = search && search?.transform?.(keys[dataIndex as string]);
          if (transformedValue !== undefined) {
            transformData = transformedValue;
            transformKey = dataIndex as string;
          }
        }
      });
      return {
        transformData,
        transformKey,
      };
    };

    //触发查询
    const handleFormSubmit = (isReset = false) => {
      form.validateFields().then((values) => {
        const { transformData, transformKey } = transformVal(removeEmptyOrNull(values));
        if (transformData && transformKey) {
          onSearch && onSearch(removeEmptyOrNull({ ...values, ...transformData }, transformKey), isReset);
          return;
        }
        onSearch && onSearch(removeEmptyOrNull(values), isReset);
      });
    };
    //触发重置
    const handleFormReset = () => {
      form.resetFields();
      handleFormSubmit(true);
    };
    //返回方法，用于父组件调用
    useImperativeHandle(ref, () => ({
      form,
      handleFormReset,
      handleFormSubmit,
    }));
    //表单搜索的自定义和默认显示操作
    const RenderBtn = useMemo(() => {
      return search && search.operateRender && search.operateRender(form);
    }, []);
    const renderItem = (item: any, form: formRef) => item.renderFormItem(item, form);
    return (
      <Form
        form={form}
        {...formProps}
        onValuesChange={(changedValues, allValues) => {
          const { transformData, transformKey } = transformVal(changedValues);
          if (transformData && transformKey) {
            onChangeSearch && onChangeSearch(transformData, allValues);
            return;
          }
          onChangeSearch && onChangeSearch(changedValues, allValues);
        }}
      >
        {formItems &&
          formItems.map((item, index) => (
            <div key={index}>
              <Form.Item
                initialValue={item?.initialValue ?? null}
                name={item.dataIndex as string}
                {...item.formItemProps}
                label={typeof item.title === 'function' ? item.title({}) : item.title}
                style={{ marginRight: '10px' }}
              >
                {item.renderFormItem ? renderItem(item, form) : <Input />}
              </Form.Item>
            </div>
          ))}
        {/* 操作按钮 */}
        {formProps.layout == 'inline' && (
          <Form.Item style={{ display: 'flex', alignItems: 'flex-end', marginLeft: 'auto' }}>
            <div style={{ display: 'flex', gap: '8px' }}>
              {search && search.operateRender ? (
                /* 自定义操作栏 */
                <div>{RenderBtn && RenderBtn.map((el: any, index) => <div key={index}>{el}</div>)}</div>
              ) : (
                /* 默认操作栏 提交，重置 */
                <div style={{ display: 'flex', gap: '10px' }}>
                  <Button type='primary' size='middle' onClick={handleFormSubmit as any} loading={loading}>
                    {search && search.searchText}
                  </Button>
                  <Button size='middle' onClick={handleFormReset}>
                    {search && search.resetText}
                  </Button>
                </div>
              )}
            </div>
          </Form.Item>
        )}
      </Form>
    );
  }
);
export default SearchBar;
